package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.AttrGroupService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrResp;
import com.atguigu.gulimall.product.vo.AttrResponseVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        //1.保存属性
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);

        this.save(attrEntity);
        //2保存关联数据
        if(attr.getAttrType()!=ProductConstant.attrConstant.SALE_ATTR.getCode()){
            AttrAttrgroupRelationEntity attrRelation = new AttrAttrgroupRelationEntity();
            attrRelation.setAttrId(attrEntity.getAttrId());
            attrRelation.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationService.save(attrRelation);
        }
    }

    @Transactional
    @Override
    public PageUtils queryAttrInfo(Map<String, Object> params, Long catelogId,String attrType) {
        //封装插查询条件
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(attrType)?ProductConstant.attrConstant.BASE_ATTR.getCode():ProductConstant.attrConstant.SALE_ATTR.getCode());
        String key = (String) params.get("key");
        IPage<AttrEntity> page =null;
        if(StringUtils.isNotEmpty(key)){
            queryWrapper.and(item->{
                item.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        //根据分类id，判断是否查询全部
        if(catelogId==0){
            //分页查询所有
            //封装分页条件
             page = new Query<AttrEntity>().getPage(params);
            this.page(page,queryWrapper);
        }
        else{
            //根据分类id查询属性
            page = new Query<AttrEntity>().getPage(params);
            queryWrapper.eq("catelog_id",catelogId);
            this.page(page,queryWrapper);
        }

        //查询分类名和所属组名
        //清除分类id
        List<AttrEntity> records = page.getRecords();
        List<AttrResp> res =
        records.stream().map(attr->{
            AttrResp attrResp = new AttrResp();
            BeanUtils.copyProperties(attr,attrResp);
            //查询分组名
            Long attrId = attr.getAttrId();
            AttrAttrgroupRelationEntity attr_id = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if(attr_id!=null&&attr_id.getAttrGroupId()!=null){
                Long attrGroupId = attr_id.getAttrGroupId();
                AttrGroupEntity byId = attrGroupService.getById(attrGroupId);
                String attrGroupName = byId.getAttrGroupName();
                attrResp.setGroupName(attrGroupName);
            }
            //查询分类名
            CategoryEntity category = categoryService.getById(attr.getCatelogId());
            if(category!=null){
                attrResp.setCatelogName(category.getName());
            }
            return attrResp;
        }).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(res);
        return pageUtils;

    }

    @Transactional
    @Override
    public AttrResponseVo getAttr(Long attrId) {
        //获取属性详细信息
        AttrEntity attrEntity = this.getById(attrId);
        AttrResponseVo attrResp = new AttrResponseVo();
        BeanUtils.copyProperties(attrEntity,attrResp);

        //获取分组id和分类完整路径
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if(relationEntity!=null){
                Long attrGroupId = relationEntity.getAttrGroupId();
                attrResp.setAttrGroupId(attrGroupId);
        }
        Long catelogId = attrEntity.getCatelogId();
        List<Long> path  = new ArrayList<>();
        path = getParent(catelogId,path);
        Collections.reverse(path);
        attrResp.setCatelogPath(path);

        return attrResp;
    }

    @Transactional
    @Override
    public void updateCascade(AttrVo attr) {
        //修改属性表
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        //修改属性和属性分组关联表
        if(attr.getAttrType()!=ProductConstant.attrConstant.SALE_ATTR.getCode()){
            Long attrId = attr.getAttrId();
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if(relationEntity!=null){
                //修改
                relationEntity.setAttrGroupId(attr.getAttrGroupId());
                attrAttrgroupRelationService.updateById(relationEntity);
            }
            else{
                //如果关联表不存在该关联关系则做添加操作
                relationEntity.setAttrGroupId(attr.getAttrGroupId());
                attrAttrgroupRelationService.save(relationEntity);
            }
        }
    }

    /**
     * 删除该分类下未被关联的属性
     * @param params 分页参数
     * @param attrGroupId 分组id
     * @return 分页数据
     */
    @Override
    public PageUtils RelationNoAttr(Map<String, Object> params, Long attrGroupId) {
        //查出分类id
        AttrGroupEntity attrGroup = attrGroupService.getById(attrGroupId);
        Long catelogId = attrGroup.getCatelogId();
        //查出当前分类的所有分组
        List<AttrGroupEntity> groups = attrGroupService.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> groupIds =
        groups.stream().map(item->
            item.getAttrGroupId()
        ).collect(Collectors.toList());
        //查出这些被关联的其他属性(查询关联表)
        List<AttrAttrgroupRelationEntity> relations = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
        List<Long> relAttr =
                relations.stream().map(item->
                        item.getAttrId())
                        .collect(Collectors.toList());

        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", ProductConstant.attrConstant.BASE_ATTR.getCode());
        IPage<AttrEntity> page = new Query<AttrEntity>().getPage(params);
        if(relAttr!=null&&relAttr.size()>0){
            queryWrapper.notIn("attr_id",relAttr);
        }
        String key = (String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            queryWrapper.and(item->{
                item.eq("attr_id",key)
                        .or()
                        .like("attr_name",key);
            });
        }
        this.page(page,queryWrapper.eq("catelog_id",catelogId));

        return new PageUtils(page);
    }

    /**
     * 根据分组id查询所有关联的属性
     * @param attrGroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));

        //获取所有id
        List<Long> attrIds =
        relationEntities.stream().map(item->
                item.getAttrId()).collect(Collectors.toList());

        //查询属性
        List<AttrEntity> attrEntities = (ArrayList)this.listByIds(attrIds);
        return attrEntities;
    }

    @Override
    public List<Long> getSearchAttrId(List<Long> attrIds) {

        return baseMapper.getSearchAttrId(attrIds);
    }

    //查询分类路径
    public List<Long> getParent(Long catId,List<Long> path){
        path.add(catId);
        CategoryEntity category = categoryService.getById(catId);
        if(category.getParentCid()!=null&&category.getParentCid()!=0L){
            getParent(category.getParentCid(),path);
        }
        return path;
    }

}